package com.chagee.channel.server.config;

import com.chagee.channel.server.enums.SubsystemEnum;
import com.lark.oapi.Client;
import java.util.Map;
import java.util.Map.Entry;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * 飞书配置
 *
 * @author: chang.jiawei
 * @date: 2024/01/15
 */
@Data
@Slf4j
@RefreshScope
@Component("larkConfig")
@ConfigurationProperties(prefix = "lark")
public class LarkConfig implements InitializingBean {

    private Application application;

    private OpenAPI openAPI;

    private Map<String, Map<String, String>> approvalCode;

    private Event event;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("LarkConfig:{}", this);
    }

    @Data
    public static class Event {

        private String encryptKey;

        private String verificationToken;
    }

    @Data
    public static class Application {

        private String appId;

        private String appSecret;
    }

    @Data
    public static class OpenAPI {

        private String tenantAccessToken;

        private String uploadFile;

        private String startApproval;

        private String approveApproval;

        private String rejectApproval;

        private String revokeApproval;

        private String approvalInstanceDetail;

        private String subscribeApproval;

        private String unsubscribeApproval;

        private String approvalInstancePreview;

        private String approvalDetail;

        private String approvalCommentList;

        private String approvalCarbonCopy;

		private String approvalInstanceComment;

    }

    @Bean
    public Client client() {
        return Client.newBuilder(application.appId, application.appSecret).build();
    }

    public SubsystemEnum fetchSubsystemByApprovalCode(String code) {
        for (Entry<String, Map<String, String>> entry : approvalCode.entrySet()) {
            SubsystemEnum subsystem = SubsystemEnum.of(entry.getKey());
            if (entry.getValue().entrySet().stream().anyMatch(t -> t.getValue().equals(code))) {
                return subsystem;
            }
        }
        return null;
    }
}
